In [5]:
import os
os.environ['HF_HOME'] = '/scratch/fd2264/cache'
from scipy.cluster import hierarchy as sch
import sys
sys.path.insert(1, '../src/')
from utils import  clean_text,Text_Topic_Extractor,set_topic_explainer_pipe,sentence_split_nltk,get_word_count, compute_and_save_embeddings, set_finetuned_topic_explainer
from visutils import plot_topic_across_time
import pandas as pd
import numpy as np
from sentence_transformers import SentenceTransformer

#python -m spacy download es_core_news_sm
/ext3/miniconda3/lib/python3.12/site-packages/dask/dataframe/__init__.py:31: FutureWarning: 
Dask dataframe query planning is disabled because dask-expr is not installed.

You can install it with `pip install dask[dataframe]` or `conda install dask`.
This will raise in a future version.

  warnings.warn(msg, FutureWarning)
In [11]:
%load_ext autoreload
%autoreload 2

Cleaning More and splitting the data into sentences¶

In [6]:
interventions = pd.read_json('../data/clean/interventions.json', orient='records')
interventions.speech = interventions.speech.apply(clean_text)
interventions['Document'] = interventions.speech.apply(sentence_split_nltk)
phrase_df = interventions.explode('Document')
phrase_df = phrase_df.drop(["speech", "word_count", "sentence_count"],axis=1)
phrase_df['word_count'] = phrase_df.Document.apply(get_word_count)
phrase_df = phrase_df[phrase_df['word_count']>15].reset_index()
speeches = phrase_df.Document

Computing the embeddings if needed¶

In [7]:
load = True
# embedding_model = SentenceTransformer("distiluse-base-multilingual-cased-v1")
approach = "sentence_NLTK"
if(not load):
    embedding_model = SentenceTransformer("distiluse-base-multilingual-cased-v1")
    compute_and_save_embeddings(embedding_model, approach)
else:
    with open(f'../data/approach_{approach}/5d_embeddings.npy', 'rb') as f:
            reduced_embeddings = np.load(f)
    with open(f'../data/approach_{approach}/2d_embeddings.npy', 'rb') as f:
            reduced_embeddings_2d = np.load(f)
    with open(f'../data/approach_{approach}/clusters.npy', 'rb') as f:
            clusters = np.load(f)
    with open(f'../data/approach_{approach}/embeddings.npy', 'rb') as f:
        embeddings = np.load(f)

Defining the topic extractor and loading¶

In [8]:
load_folder = '../data/approach_sentence_NLTK/'
topic_extractor = Text_Topic_Extractor(text_list = speeches,
                 clusters = load_folder + 'clusters.npy' ,
                 embeddings = load_folder + 'embeddings.npy',
                 reduced_embeddings = load_folder + '5d_embeddings.npy',
                 reduced_embeddings_2d = load_folder + '2d_embeddings.npy',
                 min_topic_size = 10 )

If you don't have a topic_extractor serialized you have to fit it in your documents

In [9]:
#uncomment to run fit the model 
#topic_explainer_pipe, tokenizer = set_topic_explainer_pipe()
#topic_extractor.fit(topic_explainer_pipe = topic_explainer_pipe )
#topic_extractor.save(folder_path = 'saved_models/per_sentence/')

topic_extractor.load(topic_model_path = 'saved_models/per_sentence/', topic_info_path = 'saved_models/per_sentence/topic_info.pkl' )
In [10]:
topic_extractor.clean_labels()
100%|██████████| 254/254 [00:00<00:00, 309156.48it/s]

Visualizations¶

Visualizing cluster on the embedding space¶

Using Visualize_2d_cluster we can see how topic is distributed on the embedding space. To avoid a too heavy plot, use hide_document_hover = True. If you set hide_document_hover = False, it will show the content of each document when you hover over it.

In [10]:
topic_extractor.visualize_2d_clusters(hide_document_hover = True, custom_labels = True, top_n = 10,hide_annotations = True)

Topics over time¶

A graphical representation of the distribution of the topic `Privatization of electricity' over the analyzed period. Note that on 2021 there is a surge that coincides with the introduction of a presidential reform aimed at addressing concerns surrounding the privatization of the electricity sector, as supported by corroborating news articles. https://www.reuters.com/world/americas/mexico-president-says-electricity-reform-has-been-sent-congress-2021-10-01/

By clicking on the legend the user can change the topic analyzed.

In [13]:
document_df = topic_extractor.get_document_info(phrase_df)
In [14]:
plot_topic_across_time(document_df, default=7 )
In [15]:
plot_topic_across_time(document_df,aggregation_level = 'week', title = 'Topics over Time - weekly', default = 7)
In [16]:
plot_topic_across_time(document_df,aggregation_level = 'month',title = 'Topics over Time -monthly', default = 7 )

Visualing the key-words of each topic¶

This plot shows how the importance of each key_word on each topic. Here we will analyze the key-words for the Topic "Medical attention during the pandemic". Currently we have 2 visualizations: One showing the topic word scores and other showing the WordCloud.

In [11]:
topic_extractor.topic_model.visualize_barchart(top_n_topics=1, custom_labels = True)
In [18]:
topic_extractor.create_wordcloud(topic=0)
No description has been provided for this image

Visualizing heatmap by document¶

This visualization shows how each word contributes to distinct topics. In this example, words related with "airport" are related with "airport" topics while words related with money are related with topics such as "cambio" (Exchange). With this visualization the general user can have a better understanding of what a topic means. Also, a more advanced user can use this tool to "debug" our approach.

In [34]:
topic_distr, topic_token_distr = topic_extractor.topic_model.approximate_distribution(speeches, calculate_tokens=True)
100%|██████████| 379/379 [02:49<00:00,  2.24it/s]
In [36]:
df = topic_extractor.topic_model.visualize_approximate_distribution(speeches[139341], topic_token_distr[139341])
display(df)
  En Santa Lucía estamos haciendo el aeropuerto Felipe Ángeles el mejor aeropuerto del mundo que se esté construyendo el mejor aeropuerto del mundo que se esté construyendo en la actualidad nos va costar 75 mil millones de pesos para 300 mil son 225 mil millones de ahorro
3_aeropuerto_aeropuertos_avión_aviones 0.127 0.254 0.358 0.461 0.455 0.485 0.539 0.565 0.581 0.527 0.369 0.240 0.103 0.000 0.000 0.000 0.000 0.000 0.103 0.103 0.103 0.103 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
111_jóvenes_joven_generaciones_futuro 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.231 0.462 0.693 0.900 0.669 0.439 0.208 0.000 0.000 0.231 0.462 0.693 0.802 0.571 0.340 0.109 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
152_dólar_dólares_centavos_cambio 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.108 0.216 0.320 0.423 0.315 0.207 0.104 0.000 0.000 0.000 0.000
234_presupuesto_gasto_gastos_presidencia 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.134 0.134 0.134 0.134
239_ejemplos_gas_precio_barato 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.129 0.129 0.129 0.129
247_aeropuerto_aeropuertos_puerto_tulum 0.000 0.000 0.000 0.163 0.361 0.567 0.773 0.768 0.729 0.686 0.622 0.607 0.447 0.285 0.142 0.000 0.000 0.146 0.308 0.451 0.593 0.447 0.285 0.142 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
248_ángeles_2021_aeropuerto_secretaría 0.000 0.000 0.000 0.170 0.482 0.951 1.420 1.687 1.762 1.463 1.135 0.839 0.452 0.282 0.141 0.000 0.000 0.000 0.170 0.311 0.452 0.452 0.282 0.141 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000

Similarity between topics¶

As we analyze over 300,000 sentences, several similar topics appears using distinct words even being basically the same. To help the user understaing how the topics correlate with each other, we present a similarity matrix. This matrix, computed using TF-IDF vectors and cosine similarity, reveals a cluster of closely related topics, highlighted in dark blue. Zooming in on this cluster, we observe that many topics pertain to fuel prices. Depending on the nature of the analysis, merging these topics could prove advantageous, potentially simplifying the analysis process while retaining substantive insights.

In [37]:
topic_extractor.topic_model.visualize_heatmap(custom_labels = True, n_clusters = 5)

Retrieving dataframes¶

In [39]:
df = topic_extractor.get_topic_info()
display(df)
Topic Count Name CustomName Representation Representative_Docs
0 -1 187146 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN
1 0 31094 0_hospitales_hospital_sanitaria_coronavirus Atención médica durante pandemia [hospitales, hospital, sanitaria, coronavirus,... NaN
2 1 13349 1_jueves_sábado_conferencias_miércoles Temática: Conferencias programadas [jueves, sábado, conferencias, miércoles, vier... NaN
3 2 5589 2_escuelas_educativo_educación_educativa Inicio del ciclo escolar [escuelas, educativo, educación, educativa, es... NaN
4 3 4898 3_aeropuerto_aeropuertos_avión_aviones Nuevo aeropuerto "Felipe Ángeles" [aeropuerto, aeropuertos, avión, aviones, aére... NaN
... ... ... ... ... ... ...
249 248 95 248_ángeles_2021_aeropuerto_secretaría Avances construcción AIFA [ángeles, 2021, aeropuerto, secretaría, 2022, ... NaN
250 249 93 249_mentira_mentir_propaganda_repetir Propaganda y repetición de mentiras [mentira, mentir, propaganda, repetir, alemán,... NaN
251 250 93 250_vivienda_viviendas_casas_hogares Programa de vivienda y reconstrucción [vivienda, viviendas, casas, hogares, reconstr... NaN
252 251 92 251_carta_cartas_tarjeta_tarjetas Contenido de la carta [carta, cartas, tarjeta, tarjetas, papel, escr... NaN
253 252 90 252_industrial_industria_industrias_automotriz Reconversión de industria automotriz [industrial, industria, industrias, automotriz... NaN

254 rows × 6 columns

In [14]:
document_df = topic_extractor.get_document_info(phrase_df)
display(document_df)
Document Topic Name CustomName Representation Representative_Docs Top_n_words Representative_document timestamp speaker Old_Index
0 Hemos estado de lunes a viernes con estas reun... -1 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN abogados - federales - legisladores - judicial... False 2018-12-07 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 0
1 Y lo vamos a seguir haciendo siempre de lunes ... 1 1_jueves_sábado_conferencias_miércoles Temática: Conferencias programadas [jueves, sábado, conferencias, miércoles, vier... NaN jueves - sábado - conferencias - miércoles - v... False 2018-12-07 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 0
2 La reunión la presido y participa el secretari... 11 11_militares_militar_ejército_soldados Roles y acciones de las Fuerzas [militares, militar, ejército, soldados, armad... NaN militares - militar - ejército - soldados - ar... False 2018-12-07 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 0
3 También se está invitando al fiscal general, A... 203 203_fiscal_fiscalía_confianza_confiable Confianza en Fiscal Alejandro Gertz [fiscal, fiscalía, confianza, confiable, aleja... NaN fiscal - fiscalía - confianza - confiable - al... False 2018-12-07 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 0
4 Les comentaba que poco a poco estamos ya acerc... 1 1_jueves_sábado_conferencias_miércoles Temática: Conferencias programadas [jueves, sábado, conferencias, miércoles, vier... NaN jueves - sábado - conferencias - miércoles - v... False 2018-12-07 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 0
... ... ... ... ... ... ... ... ... ... ... ...
378544 Eso es lo que quiero que hoy también plantee l... -1 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN abogados - federales - legisladores - judicial... False 2024-04-04 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 104206
378545 Y ya lleva como un año o más que envié la prim... -1 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN abogados - federales - legisladores - judicial... False 2024-04-04 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 104206
378546 Y, sí, no tenemos tratado de extradición, pero... -1 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN abogados - federales - legisladores - judicial... False 2024-04-04 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 104206
378547 Aquí lo planteo también, en el libro, por eso ... -1 -1_abogados_federales_legisladores_judicial Roles de autoridades legales y sociales [abogados, federales, legisladores, judicial, ... NaN abogados - federales - legisladores - judicial... False 2024-04-04 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 104206
378548 Entonces, sí vamos a… Hoy o mañana se pronunci... 103 103_secretaria_embajada_secretario_internacion... Asuntos de Relaciones Exteriores [secretaria, embajada, secretario, internacion... NaN secretaria - embajada - secretario - internaci... False 2024-04-04 PRESIDENTE ANDRÉS MANUEL LÓPEZ OBRADOR 104206

378549 rows × 11 columns

In [110]:
print(topic_info_recovered[topic_info_recovered.Topic == 3].Representative_Docs.to_list())
[['Imagínense la saturación, ya no es posible, y se tiene un buen aeropuerto, de los mejores aeropuertos del mundo, que es el aeropuerto ‘Felipe Ángeles’.', 'En Santa Lucía estamos haciendo el aeropuerto ‘Felipe Ángeles’, el mejor aeropuerto del mundo que se esté construyendo, el mejor aeropuerto del mundo que se esté construyendo en la actualidad, nos va a costar 75 mil millones de pesos, para 300 mil son 225 mil millones de ahorro.', 'La verdad era que querían urbanizar las 650 hectáreas del actual aeropuerto, había un proyecto para hacer una avenida que llegara hasta el nuevo aeropuerto de Texcoco y se iban a comercializar los terrenos, una especie de Santa Fe allá, en Texcoco, por eso se defendía tanto ese proyecto, y también se iba a clausurar la base aérea de Santa Lucía.']]